package Experiment;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class Car extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html,chardrt=UTF-8");
        PrintWriter out = resp.getWriter();
        HttpSession hs = req.getSession();
        Map<String, Integer> car = (Map<String, Integer>) hs.getAttribute("shoppingCar");
        //如果回话域没有shoppingcar,则实例化一个
        if (car == null) {
            car = new HashMap<String, Integer>();
        }
        //获取用户的所选择的商品
        String[] book = req.getParameterValues("book");
//        if(book!=null&&book.length>0){
//            for(int i=0;i<book.length;i++){
//                out.println(book[i]);
//            }
//        }
        if (book != null && book.length > 0) {
            for (String bookname : book) {
                //判断该物品是否在购物车中
                if (car.get(bookname) != null) {
                    int num = car.get(bookname);
                    car.put(bookname, num + 1);
                } else {
                    car.put(bookname, 1);
                }
            }
        }
        hs.setAttribute("shoppingCar", car);
        resp.sendRedirect("http://localhost:8080/javaWeb_war_exploded/Experiment/CarList");
    }
}
